# -*- coding: utf-8 -*-
import multiprocessing
import os
import sys
import shutil
import json
import codecs
import qdarktheme
import imageio
from PIL import Image
from PySide6.QtGui import *
from PySide6.QtMultimedia import QMediaPlayer, QAudioOutput

from remote import remoteThread
from GIFWidget import GIFWidget
from option import OptionWidget, KeyWords
# from giftPhysical import GiftPysical
from checkUpdate import *
from multiprocessing import Process, Queue


def showArcadeGift(queue):
    import arcade
    from giftPhysical_arcade import MyGame
    MyGame(1920, 1080, queue)
    arcade.run()


class Slider(QSlider):
    pointClicked = Signal(QPoint)

    def __init__(self):
        super(Slider, self).__init__()
        self.setOrientation(Qt.Horizontal)
        self.pressed = False

    def mousePressEvent(self, event):
        # self.pointClicked.emit(event.pos())
        self.pressed = True

    def mouseReleaseEvent(self, event):
        self.pressed = False

    def mouseMoveEvent(self, event):
        if self.pressed:
            self.pointClicked.emit(event.pos())


class previewLabel(QLabel):
    click = Signal()

    def __init__(self, text='', parent=None):
        super().__init__(parent)
        self.setText(text)
        self.setAlignment(Qt.AlignCenter)

    def mousePressEvent(self, QEvent):
        self.click.emit()


class Button(QPushButton):
    def __init__(self, txt=''):
        super(Button, self).__init__()
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.setText(txt)
        self.setStyleSheet('color:#3D3D3D')


class Label(QLabel):
    def __init__(self, txt=''):
        super(Label, self).__init__()
        self.setText(txt)
        self.setAlignment(Qt.AlignCenter)
        self.setStyleSheet('color:#3D3D3D')


class MainWindow(QMainWindow):
    def __init__(self, app, version):
        super().__init__()
        self.app = app
        self.version = version
        self.setWindowIcon(QIcon('utils/icon.png'))
        if not os.path.exists('gift'):
            os.mkdir('gift')
        self.sound = QMediaPlayer()
        self.soundOutput = QAudioOutput()
        self.sound.setAudioOutput(self.soundOutput)
        self.executeToken = False
        self.setAcceptDrops(True)
        self.installEventFilter(self)
        self.widgetsList = []
        self.loadConfig()
        self.initGIFWidget()
        self.initUI()
        # self.PVZ = None  # 互动游戏 - 植物大战僵尸

        self.giftDict = {}
        self.giftExist = {}
        self.animationToken = False
        self.timer = QTimer()
        self.timer.setInterval(50)
        self.timer.timeout.connect(self.checkGift)
        # self.timer.start()

    def loadConfig(self):
        if os.path.exists('utils/config.json') and os.path.getsize('utils/config.json'):
            with codecs.open('utils/config.json', 'r', 'utf_8_sig') as config:
                config = config.read()
            self.config = json.loads(config)
        else:
            self.config = {str(x): {'words': '感谢 {用户} 投喂', 'words2': '❤{数量}个{礼物}❤',
                                    'sound_path': '', 'volume': 60, 'gif_path': '', 'gif_scale': 50,
                                    'second': 10, 'font_color': '#3c9dca', 'out_color': '#1c54a7', 'out_size': 15,
                                    'font_name': 'Microsoft JhengHei UI', 'font_size': 30, 'font_bold': True,
                                    } for x in range(9)}
            self.config['8']['words'] = '来自 {用户} 的 {价格} 元 Super Chat：'
            self.config['8']['words2'] = '{留言}'
            self.config['room_url'] = '12345678'
            self.config['background_color'] = '#00ff00'
            self.config['opacity'] = False
            self.config['top'] = False
            self.config['check_update'] = True
            self.config['show_gift'] = True
            for index, preset in enumerate(['giftpreset1', 'giftpreset2', 'giftpreset3', 'giftpreset4',
                                            'jianzhangpreset', 'tidupreset', 'zongdupreset']):
                self.config[preset] = str(index + 1)
            self.config['0']['second'] = 2
            self.config['1']['second'] = 4
            self.config['2']['second'] = 6
            self.config['3']['second'] = 8
            self.config['4']['second'] = 10
            self.config['5']['second'] = 12
            self.config['6']['second'] = 14
            self.config['scpreset'] = '9'
            self.config['language'] = 'zh'
        if 'gift_max' not in self.config:
            self.config['gift_max'] = '800'
        self.presetIndex = '0'
        self.second = self.config['0']['second']
        self.color = self.config['0']['font_color']
        self.outColor = self.config['0']['out_color']
        self.outSize = self.config['0']['out_size']
        self.gifScale = self.config['0']['gif_scale']
        self.gifSize = None
        self.volume = self.config['0']['volume']
        # self.sound.setVolume(self.volume)
        self.soundOutput.setVolume(self.volume)
        self.oldsound = self.config['0']['sound_path']
        self.movieList = []
        self.gifSizeList = []
        for index in [str(i) for i in range(9)]:
            movie = QMovie(self.config[index]['gif_path'])
            gifSize = QPixmap(self.config[index]['gif_path']).size()
            if gifSize:
                movie.setScaledSize(gifSize * self.config[index]['gif_scale'] / 25)
            self.movieList.append(movie)
            self.gifSizeList.append(gifSize)
        self.option = OptionWidget(self.config['background_color'], self.config['opacity'], self.config['top'])
        self.option.color.connect(self.selectBackgroundColor)
        self.option.opacity.connect(self.setopacity)
        self.option.top.connect(self.setTop)
        self.keyWords = KeyWords()

        if self.config['check_update']:  # 检查更新
            self.updateChecker()

        # self.giftPhysical = GiftPysical(int(self.config['gift_max']), self.config['opacity'], self.config['top'])
        # self.giftPhysical.show()
        # self.giftPhysical.setBackgroundColor(self.config['background_color'])
        # giftPhysical_arcade.main()

        self.language = QTranslator()
        self.language.load('utils/%s.qm' % self.config['language'])
        self.app.installTranslator(self.language)

    def initGIFWidget(self):
        self.GIFWidget = GIFWidget(self.movieList[0], self.config['opacity'],
                                   self.config['top'], self.second * 60, self.color, self.outColor)
        self.GIFWidget.showText.w = self.outSize / 250
        self.GIFWidget.showText2.w = self.outSize / 250
        self.GIFWidget.setBackgroundColor(self.config['background_color'])
        self.GIFWidget.finish.connect(self.animateFinish)
        self.GIFWidget.moveDelta.connect(self.changeCenter)
        self.GIFWidget.setText(self.config['0']['words'], 'gift', line=1)
        self.GIFWidget.setText(self.config['0']['words2'], 'gift', line=2)
        w, h = self.GIFWidget.width(), self.GIFWidget.height()
        x, y = self.GIFWidget.pos().x(), self.GIFWidget.pos().y()
        self.GIFWidgetCenterPos = QPoint(x + w / 2, y + h / 2)
        self.font = QFont(self.config['0']['font_name'], self.config['0']['font_size'])
        self.GIFWidget.setFont(self.font)
        self.GIFWidget.setColor(self.color)

    def initUI(self):
        self.setWindowTitle('DD答谢机 V%s  (by 神君Channel)' % self.version)
        self.menuBar().setFont(QFont('Microsoft JhengHei UI', 10))
        self.menuBar().clear()
        self.languageMenu = self.menuBar().addMenu('语言/Language')
        chinese = QAction('中文', self, triggered=lambda: self.changeLanguage('zh'))
        chinese.setFont(QFont('Microsoft JhengHei UI', 10))
        self.languageMenu.addAction(chinese)
        japanese = QAction('日本語', self, triggered=lambda: self.changeLanguage('ja'))
        japanese.setFont(QFont('Microsoft JhengHei UI', 10))
        self.languageMenu.addAction(japanese)
        english = QAction('English', self, triggered=lambda: self.changeLanguage('en'))
        english.setFont(QFont('Microsoft JhengHei UI', 10))
        self.languageMenu.addAction(english)
        self.optionMenu = self.menuBar().addMenu(self.tr('option'))
        keyWords = QAction(self.tr('keywords'), self, triggered=self.popKeyWords)
        keyWords.setFont(QFont('Microsoft JhengHei UI', 10))
        self.optionMenu.addAction(keyWords)
        advanced = QAction(self.tr('advanced'), self, triggered=self.popOption)
        advanced.setFont(QFont('Microsoft JhengHei UI', 10))
        self.optionMenu.addAction(advanced)
        update = QAction(self.tr('check update'), self, triggered=self.updateChecker2)
        update.setFont(QFont('Microsoft JhengHei UI', 10))
        self.optionMenu.addAction(update)

        self.aboutMenu = self.menuBar().addMenu('关于')
        bilibili = QAction('使用教程', self, triggered=self.popBilibili)
        bilibili.setFont(QFont('Microsoft JhengHei UI', 10))
        self.aboutMenu.addAction(bilibili)
        gitee = QAction('开源地址', self, triggered=self.popGitee)
        gitee.setFont(QFont('Microsoft JhengHei UI', 10))
        self.aboutMenu.addAction(gitee)

        # self.gameMenu = self.menuBar().addMenu('互动游戏')
        # PVZ = QAction('植物大战僵尸', self, triggered=self.popPVZ)
        # PVZ.setFont(QFont('Microsoft JhengHei UI', 10))
        # self.gameMenu.addAction(PVZ)

        self.main_widget = QWidget()
        self.main_widget.setAcceptDrops(True)
        self.setCentralWidget(self.main_widget)
        layout = QGridLayout()
        layout.setSpacing(15)
        self.main_widget.setLayout(layout)
        self.roomIDLabel = Label(self.tr('bilibili live room'))
        self.roomIDLabel.setAlignment(Qt.AlignCenter)
        # layout.addWidget(self.roomIDLabel, 0, 0, 1, 1)
        self.biliLiveLabel = Label('https://live.bilibili.com/')
        layout.addWidget(self.biliLiveLabel, 0, 0, 1, 3)
        self.roomURLEdit = QLineEdit(self.config['room_url'])
        self.roomURLEdit.setValidator(QIntValidator(0, 2000000000))
        self.roomURLEdit.textChanged.connect(self.setURL)
        self.roomURLEdit.setMinimumWidth(130)
        layout.addWidget(self.roomURLEdit, 0, 3, 1, 1)

        # self.advancedButton = Button('高级设置')
        # self.advancedButton.clicked.connect(self.popOption)
        # layout.addWidget(self.advancedButton, 7, 0, 1, 1)

        self.giftGroup = QGroupBox(self.tr('GIFT'))
        self.giftGroup.setStyleSheet('QGroupBox{border-bottom:none;border-left:none;border-right:none}'
                                'QGroupBox::title{margin-top:-10px;subcontrol-position:top}')
        layout.addWidget(self.giftGroup, 1, 0, 1, 4)

        layout.addWidget(QLabel(self.tr('free gift')), 2, 0, 1, 1)
        self.giftPreset1 = QComboBox()
        self.giftPreset1.addItems([self.tr('hide')] + [self.tr('preset') + str(i) for i in range(1, 10)])
        self.giftPreset1.setCurrentIndex(int(self.config['giftpreset1']))
        self.giftPreset1.currentIndexChanged.connect(lambda x: self.switchPreset('giftpreset1', x))
        layout.addWidget(self.giftPreset1, 2, 2, 1, 1)
        self.giftPreset1Test = Button(self.tr('preview'))
        self.giftPreset1Test.clicked.connect(lambda x: self.previewPreset('giftpreset1', self.giftPreset1.currentIndex()))
        layout.addWidget(self.giftPreset1Test, 2, 3, 1, 1)

        layout.addWidget(QLabel(self.tr('0.1-10 Yuan')), 3, 0, 1, 1)
        self.giftPreset2 = QComboBox()
        self.giftPreset2.addItems([self.tr('hide')] + [self.tr('preset') + str(i) for i in range(1, 10)])
        self.giftPreset2.setCurrentIndex(int(self.config['giftpreset2']))
        self.giftPreset2.currentIndexChanged.connect(lambda x: self.switchPreset('giftpreset2', x))
        layout.addWidget(self.giftPreset2, 3, 2, 1, 1)
        self.giftPreset2Test = Button(self.tr('preview'))
        self.giftPreset2Test.clicked.connect(lambda x: self.previewPreset('giftpreset2', self.giftPreset2.currentIndex()))
        layout.addWidget(self.giftPreset2Test, 3, 3, 1, 1)

        layout.addWidget(QLabel(self.tr('10.1-100 Yuan')), 4, 0, 1, 1)
        self.giftPreset3 = QComboBox()
        self.giftPreset3.addItems([self.tr('hide')] + [self.tr('preset') + str(i) for i in range(1, 10)])
        self.giftPreset3.setCurrentIndex(int(self.config['giftpreset3']))
        self.giftPreset3.currentIndexChanged.connect(lambda x: self.switchPreset('giftpreset3', x))
        layout.addWidget(self.giftPreset3, 4, 2, 1, 1)
        self.giftPreset3Test = Button(self.tr('preview'))
        self.giftPreset3Test.clicked.connect(lambda x: self.previewPreset('giftpreset3', self.giftPreset3.currentIndex()))
        layout.addWidget(self.giftPreset3Test, 4, 3, 1, 1)

        layout.addWidget(QLabel(self.tr('> 100 Yuan')), 5, 0, 1, 1)
        self.giftPreset4 = QComboBox()
        self.giftPreset4.addItems([self.tr('hide')] + [self.tr('preset') + str(i) for i in range(1, 10)])
        self.giftPreset4.setCurrentIndex(int(self.config['giftpreset4']))
        self.giftPreset4.currentIndexChanged.connect(lambda x: self.switchPreset('giftpreset4', x))
        layout.addWidget(self.giftPreset4, 5, 2, 1, 1)
        self.giftPreset4Test = Button(self.tr('preview'))
        self.giftPreset4Test.clicked.connect(lambda x: self.previewPreset('giftpreset4', self.giftPreset4.currentIndex()))
        layout.addWidget(self.giftPreset4Test, 5, 3, 1, 1)

        guardGroup = QGroupBox(self.tr('GUARD'))
        guardGroup.setStyleSheet('QGroupBox{border-bottom:none;border-left:none;border-right:none}'
                                'QGroupBox::title{margin-top:-10px;subcontrol-position:top}')
        layout.addWidget(guardGroup, 6, 0, 1, 4)

        layout.addWidget(QLabel('舰长'), 7, 0, 1, 1)
        self.jianzhangPreset = QComboBox()
        self.jianzhangPreset.addItems([self.tr('hide')] + [self.tr('preset') + str(i) for i in range(1, 10)])
        self.jianzhangPreset.setCurrentIndex(int(self.config['jianzhangpreset']))
        self.jianzhangPreset.currentIndexChanged.connect(lambda x: self.switchPreset('jianzhangpreset', x))
        layout.addWidget(self.jianzhangPreset, 7, 2, 1, 1)
        self.jianzhangTest = Button(self.tr('preview'))
        self.jianzhangTest.clicked.connect(lambda x: self.previewPreset('jianzhangpreset', self.jianzhangPreset.currentIndex()))
        layout.addWidget(self.jianzhangTest, 7, 3, 1, 1)

        layout.addWidget(QLabel('提督'), 8, 0, 1, 1)
        self.tiduPreset = QComboBox()
        self.tiduPreset.addItems([self.tr('hide')] + [self.tr('preset') + str(i) for i in range(1, 10)])
        self.tiduPreset.setCurrentIndex(int(self.config['tidupreset']))
        self.tiduPreset.currentIndexChanged.connect(lambda x: self.switchPreset('tidupreset', x))
        layout.addWidget(self.tiduPreset, 8, 2, 1, 1)
        self.tiduTest = Button(self.tr('preview'))
        self.tiduTest.clicked.connect(lambda x: self.previewPreset('tidupreset', self.tiduPreset.currentIndex()))
        layout.addWidget(self.tiduTest, 8, 3, 1, 1)

        layout.addWidget(QLabel('总督'), 9, 0, 1, 1)
        self.zongduPreset = QComboBox()
        self.zongduPreset.addItems([self.tr('hide')] + [self.tr('preset') + str(i) for i in range(1, 10)])
        self.zongduPreset.setCurrentIndex(int(self.config['zongdupreset']))
        self.zongduPreset.currentIndexChanged.connect(lambda x: self.switchPreset('zongdupreset', x))
        layout.addWidget(self.zongduPreset, 9, 2, 1, 1)
        self.zongduTest = Button(self.tr('preview'))
        self.zongduTest.clicked.connect(lambda x: self.previewPreset('zongdupreset', self.zongduPreset.currentIndex()))
        layout.addWidget(self.zongduTest, 9, 3, 1, 1)

        SCGroup = QGroupBox('SUPER CHAT')
        SCGroup.setStyleSheet('QGroupBox{border-bottom:none;border-left:none;border-right:none}'
                                 'QGroupBox::title{margin-top:-10px;subcontrol-position:top}')
        layout.addWidget(SCGroup, 10, 0, 1, 4)

        layout.addWidget(QLabel('SC'), 11, 0, 1, 1)
        self.SCPreset = QComboBox()
        self.SCPreset.addItems([self.tr('hide')] + [self.tr('preset') + str(i) for i in range(1, 10)])
        self.SCPreset.setCurrentIndex(int(self.config['scpreset']))
        self.SCPreset.currentIndexChanged.connect(lambda x: self.switchPreset('scpreset', x))
        layout.addWidget(self.SCPreset, 11, 2, 1, 1)
        self.SCTest = Button(self.tr('preview'))
        self.SCTest.clicked.connect(lambda x: self.previewPreset('scpreset', self.SCPreset.currentIndex()))
        layout.addWidget(self.SCTest, 11, 3, 1, 1)

        self.physicalButton = Button(self.tr('display gift'))
        self.physicalButton.clicked.connect(self.changeShowGift)
        if self.config['show_gift']:
            self.queue = Queue()
            self.showGift = Process(target=showArcadeGift, args=(self.queue,))
            self.showGift.start()

            color = self.config['background_color']
            self.queue.put((int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)))

            # self.giftPhysical.show()
            self.physicalButton.setStyleSheet('background-color:#87CEFA')
        else:
            # self.giftPhysical.hide()
            self.physicalButton.setStyleSheet('background-color:#f8f9fa')
        layout.addWidget(self.physicalButton, 12, 0, 1, 2)

        layout.addWidget(QLabel(self.tr('max')), 12, 2, 1, 1)
        self.giftMax = QLineEdit(self.config['gift_max'])
        self.giftMax.setValidator(QIntValidator(10, 2000))
        self.giftMax.textChanged.connect(self.setGiftMax)
        self.giftMax.setMinimumWidth(130)
        layout.addWidget(self.giftMax, 12, 3, 1, 1)

        self.startButton = Button(self.tr('START TRIGGER'))
        self.startButton.clicked.connect(self.startMonitor)
        # self.startButton.setFixedHeight(145)
        self.startButton.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.startButton.setStyleSheet('border:2px solid #87CEFA')
        layout.addWidget(self.startButton, 13, 0, 3, 4)

        splitLine = Label()
        splitLine.setFrameStyle(QFrame.HLine | QFrame.Raised)
        splitLine.setFixedWidth(1)
        splitLine.setStyleSheet('background-color:gray')
        layout.addWidget(splitLine, 0, 7, 16, 1)

        ######################################################

        self.presetTab = QTabWidget(self)
        self.presetTab.setMaximumHeight(self.presetTab.tabBar().height() + 3)

        # self.presetButtons = []
        for i in range(9):
            self.presetTab.addTab(QWidget(), self.tr('preset') + str(i + 1))
            # self.presetButtons.append(Button('预设 %s' % (i + 1)))
            # layout.addWidget(self.presetButtons[-1], 0, 8 + i)
        layout.addWidget(self.presetTab, 0, 8, 1, 9)

        self.animeSecond = Label(self.tr('duration'))
        self.animeSecond.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.animeSecond, 1, 8, 1, 2)
        self.animeSecondComboBox = QComboBox()
        self.animeSecondComboBox.addItems([str(i) + self.tr(' second') for i in range(1, 31)])
        self.animeSecondComboBox.setCurrentIndex(self.second - 1)
        self.animeSecondComboBox.currentIndexChanged.connect(self.setSecond)
        layout.addWidget(self.animeSecondComboBox, 1, 10, 1, 2)

        self.scaledValue = Label(self.tr('picture size'))
        self.scaledValue.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.scaledValue, 1, 12, 1, 2)
        self.scaledBar = Slider()
        # self.scaledBar.setPageStep(10)  # 步长
        # self.scaledBar.setTickPosition(QSlider.TicksBelow)
        # self.scaledBar.setTickInterval(10)
        self.scaledBar.setValue(self.gifScale)
        self.scaledBar.pointClicked.connect(self.scaleChange)
        layout.addWidget(self.scaledBar, 1, 14, 1, 3)

        self.preview = previewLabel(self.tr('click to select or drag in picture/gif to display'))
        self.preview.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.preview.setFrameShape(QFrame.Box)
        self.preview.setStyleSheet('border:2px dotted #cfcfd0')
        # self.preview.setFixedSize(self.preview.size())
        # self.preview.setFixedHeight(400)
        self.preview.click.connect(self.click)
        if self.config['0']['gif_path']:
            self.gifSize = self.gifSizeList[0]
            self.movie = self.movieList[0]
            self.movie.setScaledSize(self.gifSize * self.gifScale / 25)
            self.preview.setMovie(self.movie)
            self.movie.start()
        layout.addWidget(self.preview, 2, 8, 8, 9)

        self.defaultWordsButton = Button(self.tr('words 1'))
        self.defaultWordsButton.clicked.connect(self.setDefaultWords)
        layout.addWidget(self.defaultWordsButton, 10, 8, 1, 2)
        self.wordsEdit = QLineEdit(self.config['0']['words'])
        self.wordsEdit.textChanged.connect(self.setWords)
        layout.addWidget(self.wordsEdit, 10, 10, 1, 7)

        self.defaultWordsButton2 = Button(self.tr('words 2'))
        self.defaultWordsButton2.clicked.connect(self.setDefaultWords2)
        layout.addWidget(self.defaultWordsButton2, 11, 8, 1, 2)
        self.wordsEdit2 = QLineEdit(self.config['0']['words2'])
        self.wordsEdit2.textChanged.connect(self.setWords2)
        layout.addWidget(self.wordsEdit2, 11, 10, 1, 7)

        layout.addWidget(Label(self.tr('font set')), 12, 8, 1, 2)
        self.fontCombox = QComboBox(self)
        layout.addWidget(self.fontCombox, 12, 10, 1, 5)
        fontList = QFontDatabase().families()
        self.fontCombox.addItems(fontList)
        self.fontCombox.setCurrentText(self.config[self.presetIndex]['font_name'])
        self.fontCombox.currentTextChanged.connect(self.changeFontName)

        self.fontSizeEdit = QSpinBox(self)
        self.fontSizeEdit.setValue(self.config[self.presetIndex]['font_size'])
        self.fontSizeEdit.valueChanged.connect(self.changeFontSize)
        layout.addWidget(self.fontSizeEdit, 12, 15, 1, 1)

        self.fontBoldButton = Button(self.tr('bold'))
        if self.config[self.presetIndex]['font_bold']:
            self.fontBoldButton.setStyleSheet('background-color:#87CEFA')
        self.fontBoldButton.clicked.connect(self.changeFontBold)
        layout.addWidget(self.fontBoldButton, 12, 16, 1, 1)

        self.fontColorButton = Button(self.tr('font color'))
        self.fontColorButton.clicked.connect(self.setFontColor)
        layout.addWidget(self.fontColorButton, 13, 8, 1, 2)
        self.fontColorLabel = Label()
        self.fontColorLabel.setStyleSheet('background-color:' + self.color)
        layout.addWidget(self.fontColorLabel, 13, 10, 1, 2)

        self.outLineButton = Button(self.tr('font border'))
        self.outLineButton.clicked.connect(self.setOutLine)
        layout.addWidget(self.outLineButton, 14, 8, 1, 2)
        self.outLineLabel = Label()
        self.outLineLabel.setStyleSheet('background-color:' + self.outColor)
        layout.addWidget(self.outLineLabel, 14, 10, 1, 2)
        self.outLineSizeLabel = Label(self.tr('weight'))
        layout.addWidget(self.outLineSizeLabel, 14, 12, 1, 2)
        self.outLineSizeBar = Slider()
        self.outLineSizeBar.setMaximum(100)
        self.outLineSizeBar.setValue(self.outSize)
        self.outLineSizeBar.pointClicked.connect(self.sizeChange)
        layout.addWidget(self.outLineSizeBar, 14, 14, 1, 3)

        self.soundButton = Button(self.tr('sound'))
        self.soundButton.clicked.connect(self.selectsound)
        layout.addWidget(self.soundButton, 15, 8, 1, 2)
        self.soundEdit = Label(os.path.split(self.config['0']['sound_path'])[1])
        # self.sound.setMedia(QUrl.fromLocalFile(self.config['0']['sound_path']))
        self.sound.setSource(QUrl.fromLocalFile(self.config['0']['sound_path']))
        layout.addWidget(self.soundEdit, 15, 10, 1, 2)
        self.volumeLabel = Label(self.tr('volume'))
        self.volumeLabel.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.volumeLabel, 15, 12, 1, 2)
        self.volumeBar = Slider()
        self.volumeBar.setMaximum(100)
        self.volumeBar.setValue(self.volume)
        self.volumeBar.pointClicked.connect(self.changevolume)
        layout.addWidget(self.volumeBar, 15, 14, 1, 3)

        self.presetTab.currentChanged.connect(self.changePreset)

        self.widgetsList = [self.roomURLEdit, self.defaultWordsButton, self.presetTab, self.fontBoldButton,
                            self.defaultWordsButton, self.defaultWordsButton2, self.fontCombox, self.fontSizeEdit,
                            self.fontColorButton, self.wordsEdit, self.wordsEdit2, self.outLineButton,
                            self.outLineSizeBar, self.soundButton, self.volumeBar, self.animeSecondComboBox,
                            self.scaledBar, self.preview, self.outLineSizeLabel, self.volumeLabel, self.scaledValue,
                            self.animeSecond, self.soundEdit, self.roomIDLabel, self.biliLiveLabel, self.fontColorLabel,
                            self.outLineLabel, self.giftPreset1, self.giftPreset1Test, self.giftPreset2,
                            self.giftPreset2Test, self.giftPreset3, self.giftPreset3Test, self.giftPreset4,
                            self.giftPreset4Test, self.jianzhangPreset, self.jianzhangTest, self.tiduPreset,
                            self.tiduTest, self.zongduPreset, self.zongduTest, self.SCPreset, self.SCTest]
        self.adjustSize()

    def switchPreset(self, preset, index):
        self.config[preset] = str(index)

    def previewPreset(self, preset, index):
        if index:
            self.presetIndex = str(index - 1)
            self.presetTab.setCurrentIndex(index - 1)
            if preset == 'giftpreset1':
                self.GIFWidget.setText(self.wordsEdit.text(), 'gift', True, line=1, giftInfo=['DD', '100', '小心心', '0'])
                self.GIFWidget.setText(self.wordsEdit2.text(), 'gift', True, line=2, giftInfo=['DD', '100', '小心心', '0'])
            elif preset == 'giftpreset2':
                self.GIFWidget.setText(self.wordsEdit.text(), 'gift', True, line=1, giftInfo=['DD', '1', '这个好诶', '1'])
                self.GIFWidget.setText(self.wordsEdit2.text(), 'gift', True, line=2, giftInfo=['DD', '1', '这个好诶', '1'])
            elif preset == 'giftpreset3':
                self.GIFWidget.setText(self.wordsEdit.text(), 'gift', True, line=1, giftInfo=['DD', '1', '告白花束', '22'])
                self.GIFWidget.setText(self.wordsEdit2.text(), 'gift', True, line=2, giftInfo=['DD', '1', '告白花束', '22'])
            elif preset == 'giftpreset4':
                self.GIFWidget.setText(self.wordsEdit.text(), 'gift', True, line=1, giftInfo=['DD', '1', '探索者启航', '2233'])
                self.GIFWidget.setText(self.wordsEdit2.text(), 'gift', True, line=2, giftInfo=['DD', '1', '探索者启航', '2233'])
            elif preset == 'jianzhangpreset':
                self.GIFWidget.setText(self.wordsEdit.text(), 'guard', True, line=1, giftInfo=['DD', '1', '舰长', '198'])
                self.GIFWidget.setText(self.wordsEdit2.text(), 'guard', True, line=2, giftInfo=['DD', '1', '舰长', '198'])
            elif preset == 'tidupreset':
                self.GIFWidget.setText(self.wordsEdit.text(), 'guard', True, line=1, giftInfo=['DD', '1', '提督', '1998'])
                self.GIFWidget.setText(self.wordsEdit2.text(), 'guard', True, line=2, giftInfo=['DD', '1', '提督', '1998'])
            elif preset == 'zongdupreset':
                self.GIFWidget.setText(self.wordsEdit.text(), 'guard', True, line=1, giftInfo=['DD', '1', '总督', '19998'])
                self.GIFWidget.setText(self.wordsEdit2.text(), 'guard', True, line=2, giftInfo=['DD', '1', '总督', '19998'])
            elif preset == 'scpreset':
                self.GIFWidget.setText(self.wordsEdit.text(), 'sc', True, line=1, giftInfo=['DD', '1', '主播生日快乐！！！', '50'])
                self.GIFWidget.setText(self.wordsEdit2.text(), 'sc', True, line=2, giftInfo=['DD', '1', '主播生日快乐！！！', '50'])
            self.play()

    def changePreset(self, index):
        self.presetIndex = str(index)
        self.second = self.config[self.presetIndex]['second']
        self.animeSecondComboBox.setCurrentIndex(self.second - 1)
        self.GIFWidget.setSecond(self.second)
        self.color = self.config[self.presetIndex]['font_color']
        self.font = QFont(self.config[self.presetIndex]['font_name'], self.config[self.presetIndex]['font_size'])
        if self.config[self.presetIndex]['font_bold']:
            self.font.setBold(self.config[self.presetIndex]['font_bold'])
        self.fontColorLabel.setStyleSheet('background-color:' + self.color)
        self.GIFWidget.setFont(self.font)
        self.GIFWidget.showText.setBrush(QColor(self.color))
        self.GIFWidget.showText2.setBrush(QColor(self.color))

        self.wordsEdit.setText(self.config[self.presetIndex]['words'])
        self.wordsEdit2.setText(self.config[self.presetIndex]['words2'])
        self.fontCombox.setCurrentText(self.config[self.presetIndex]['font_name'])
        self.fontSizeEdit.setValue(self.config[self.presetIndex]['font_size'])
        if self.config[self.presetIndex]['font_bold']:
            self.fontBoldButton.setStyleSheet('background-color:#87CEFA')
        else:
            self.fontBoldButton.setStyleSheet('background-color:#f8f9fa')

        self.outColor = self.config[self.presetIndex]['out_color']

        self.config[self.presetIndex]['out_color'] = self.outColor
        self.GIFWidget.showText.setPen(self.outColor)
        self.GIFWidget.showText.repaint()
        self.GIFWidget.showText2.setPen(self.outColor)
        self.GIFWidget.showText2.repaint()
        # self.outLineLabel.setText(self.outColor)
        self.outLineLabel.setStyleSheet('background-color:' + self.outColor)

        self.outSize = self.config[self.presetIndex]['out_size']

        self.outLineSizeBar.setValue(self.outSize)
        self.config[self.presetIndex]['out_size'] = self.outSize
        self.GIFWidget.showText.w = self.outSize / 250
        self.GIFWidget.showText.repaint()
        self.GIFWidget.showText2.w = self.outSize / 250
        self.GIFWidget.showText2.repaint()

        self.preview.clear()
        self.GIFWidget.showGIF.clear()
        self.preview.setText(self.tr('click to select or drag in picture/gif to display'))
        if self.config[self.presetIndex]['gif_path']:
            self.movie = self.movieList[index]
            self.gifSize = self.gifSizeList[index]
            pos = self.config[self.presetIndex]['gif_scale']
            self.scaledBar.setValue(pos)
            if self.gifSize:
                self.movie.setScaledSize(self.gifSize * pos / 25)
            self.preview.setMovie(self.movie)
            self.GIFWidget.showGIF.setMovie(self.movie)
            self.movie.start()

        self.soundEdit.setText(os.path.split(self.config[self.presetIndex]['sound_path'])[1])
        # self.sound.setMedia(QUrl.fromLocalFile(self.config[self.presetIndex]['sound_path']))
        self.sound.setSource(QUrl.fromLocalFile(self.config[self.presetIndex]['sound_path']))

        self.volume = self.config[self.presetIndex]['volume']
        self.volumeBar.setValue(self.volume)
        # self.sound.setVolume(self.volume)
        self.soundOutput.setVolume(self.volume)

    def setURL(self, text):
        self.config['room_url'] = text

    def setGiftMax(self, text):
        if text:
            self.config['gift_max'] = text
            self.giftPhysical.giftMax = int(text)

    def setWords(self, text):
        self.GIFWidget.setText(text, 'gift', line=1)
        self.config[self.presetIndex]['words'] = text

    def setWords2(self, text):
        self.GIFWidget.setText(text, 'gift', line=2)
        self.config[self.presetIndex]['words2'] = text

    def setDefaultWords(self):
        if self.presetIndex != '8':
            text = '感谢 {用户} 投喂'
        else:
            text = '来自 {用户} 的 {价格} 元 Super Chat：'
        self.GIFWidget.setText(text, 'gift', line=1)
        self.wordsEdit.setText(text)
        self.config[self.presetIndex]['words'] = text

    def setDefaultWords2(self):
        if self.presetIndex != '8':
            text = '❤{数量}个{礼物}❤'
        else:
            text = '{礼物}'
        self.GIFWidget.setText(text, 'gift', line=2)
        self.wordsEdit2.setText(text)
        self.config[self.presetIndex]['words2'] = text

    def changeGift(self):
        self.config[self.presetIndex]['gift'] = self.giftEdit.text()

    def selectsound(self):
        if not os.path.exists('sound'):
            os.mkdir('sound')
        filePath = QFileDialog.getOpenFileName(self, self.tr('select sound effect'), 'sound', "*.mp3 *.wav")[0]
        if filePath:
            fileName = os.path.split(filePath)[1]
            if not os.path.exists(r'sound/%s' % fileName):
                shutil.copy(filePath, 'sound')
            self.soundEdit.setText(os.path.split(filePath)[1])
            # self.sound.setMedia(QUrl.fromLocalFile(filePath))
            self.sound.setSource(QUrl.fromLocalFile(filePath))
            self.config[self.presetIndex]['sound_path'] = filePath
        else:
            self.soundEdit.setText('')
            # self.sound.setMedia(QUrl.fromLocalFile(''))
            self.sound.setSource(QUrl.fromLocalFile(''))
            self.config[self.presetIndex]['sound_path'] = ''

    def changevolume(self, p):
        pos = p.x() / self.volumeBar.width() * 100
        if pos > 100:
            pos = 100
        elif pos < 0:
            pos = 0
        self.volumeBar.setValue(pos)
        self.volume = pos
        # self.sound.setVolume(pos)
        self.soundOutput.setVolume(pos)
        self.config[self.presetIndex]['volume'] = pos

    def selectBackgroundColor(self, color):
        self.config['background_color'] = color
        self.GIFWidget.setBackgroundColor(color)
        # self.giftPhysical.setBackgroundColor(color)
        self.queue.put((int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)))

    def setTop(self, topToken):
        self.config['top'] = topToken

    def setopacity(self, opacityToken):
        self.config['opacity'] = opacityToken

    def setSecond(self, index):
        self.second = index + 1
        self.GIFWidget.setSecond(self.second)
        self.config[self.presetIndex]['second'] = self.second

    def scaleChange(self, p):
        pos = p.x() / self.scaledBar.width() * 100
        if pos > 100:
            pos = 100
        elif pos < 1:
            pos = 1
        self.scaledBar.setValue(pos)
        self.config[self.presetIndex]['gif_scale'] = pos
        scale = pos / 25
        if self.gifSize:
            self.movie.setScaledSize(self.gifSize * scale)

    def sizeChange(self, p):
        self.outSize = p.x() / self.outLineSizeBar.width() * 100
        if self.outSize > 100:
            self.outSize = 100
        elif self.outSize < 1:
            self.outSize = 1
        self.outLineSizeBar.setValue(self.outSize)
        self.config[self.presetIndex]['out_size'] = self.outSize
        self.GIFWidget.showText.w = self.outSize / 400
        self.GIFWidget.showText.repaint()
        self.GIFWidget.showText2.w = self.outSize / 400
        self.GIFWidget.showText2.repaint()

    def click(self):
        filePath = QFileDialog.getOpenFileName(self, self.tr('select picture or gif'), 'gif', "*.gif *.jpg *.png;;All Files (*.*)")[0]
        if filePath:
            self.openFile(filePath)
        else:
            self.preview.clear()
            self.GIFWidget.showGIF.clear()
            self.preview.setText(self.tr('click to select or drag in picture/gif to display'))
            self.config[self.presetIndex]['gif_path'] = ''

    def openFile(self, filePath):
        fileName = os.path.split(filePath)[1]
        if not os.path.exists('gif'):
            os.mkdir('gif')
        if fileName.lower().endswith('.gif'):
            if not os.path.exists(r'gif/%s' % fileName):
                shutil.copy(filePath, 'gif')
            filePath = r'%s/gif/%s' % (os.getcwd(), fileName)
        elif fileName.lower().endswith('.png'):
            imgs = []
            for i in range(2):
                im = Image.open(filePath)
                alpha = im.getchannel('A')
                im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)
                mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
                im.paste(255, mask)
                im.info['transparency'] = 255
                imgs.append(im)
            filePath = r'gif/%s.gif' % fileName.split('.')[0]
            imgs[0].save(filePath, save_all=True, append_images=imgs[1:], optimize=False, duration=100, loop=0)
        else:
            frames = [imageio.imread(filePath)]
            filePath = r'gif/%s.gif' % fileName.split('.')[0]
            imageio.mimsave(filePath, frames, 'GIF', duration=0.1)
        self.gifSize = QPixmap(filePath).size()
        index = self.presetTab.currentIndex()
        self.movieList[index] = QMovie(filePath)
        self.gifSizeList[index] = self.gifSize
        self.movie = self.movieList[index]
        self.preview.setMovie(self.movie)
        self.GIFWidget.showGIF.setMovie(self.movie)
        self.movie.start()
        # self.GIFWidget.setGIFPath(filePath)
        self.config[self.presetIndex]['gif_path'] = filePath
        self.scaledBar.setValue(50)
        self.config[self.presetIndex]['gif_scale'] = 50
        scale = 2
        if self.gifSize:
            self.movie.setScaledSize(self.gifSize * scale)

    def dragEnterEvent(self, QDragEnterEvent):
        QDragEnterEvent.accept()

    def dropEvent(self, QEvent):
        if QEvent.mimeData().hasUrls:
            self.openFile(QEvent.mimeData().urls()['0'].toLocalFile())

    def closeEvent(self, QCloseEvent):
        self.GIFWidget.exit = True
        self.GIFWidget.close()
        self.option.close()
        self.keyWords.close()
        # self.giftPhysical.close()
        with codecs.open('utils/config.json', 'w', 'utf_8_sig') as config:
            config.write(json.dumps(self.config, ensure_ascii=False))
        try:
            self.showGift.terminate()
            self.showGift.join()
            self.showGift.close()
        except:
            pass

    def changeFontName(self, fontName):
        self.config[self.presetIndex]['font_name'] = fontName
        self.setGIFWidgetFont()

    def changeFontSize(self, fontSize):
        self.config[self.presetIndex]['font_size'] = fontSize
        self.setGIFWidgetFont()

    def changeFontBold(self):
        self.config[self.presetIndex]['font_bold'] = not self.config[self.presetIndex]['font_bold']
        if self.config[self.presetIndex]['font_bold']:
            self.fontBoldButton.setStyleSheet('background-color:#87CEFA')
        else:
            self.fontBoldButton.setStyleSheet('background-color:#f8f9fa')
        self.setGIFWidgetFont()

    def changeShowGift(self):
        self.config['show_gift'] = not self.config['show_gift']
        if self.config['show_gift']:
            self.queue = Queue()
            self.showGift = Process(target=showArcadeGift, args=(self.queue,))
            self.showGift.start()

            color = self.config['background_color']
            self.queue.put((int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)))

            # self.giftPhysical.show()
            self.physicalButton.setStyleSheet('background-color:#87CEFA')
        else:
            self.showGift.terminate()
            self.showGift.join()
            # self.giftPhysical.hide()
            self.physicalButton.setStyleSheet('background-color:#f8f9fa')

    def setGIFWidgetFont(self):
        font = QFont(self.config[self.presetIndex]['font_name'], self.config[self.presetIndex]['font_size'])
        font.setBold(self.config[self.presetIndex]['font_bold'])
        self.GIFWidget.setFont(font)

    def setFontColor(self):
        color = QColorDialog().getColor(self.color)
        if color.isValid():
            self.color = color.name()
            self.config[self.presetIndex]['font_color'] = self.color
            self.GIFWidget.showText.setBrush(QColor(self.color))
            self.GIFWidget.showText.repaint()
            self.GIFWidget.showText2.setBrush(QColor(self.color))
            self.GIFWidget.showText2.repaint()
            self.fontColorLabel.setStyleSheet('background-color:' + self.color)

    def setOutLine(self):
        color = QColorDialog().getColor(self.outColor)
        if color.isValid():
            self.outColor = color.name()
            self.config[self.presetIndex]['out_color'] = self.outColor
            self.GIFWidget.showText.setPen(self.outColor)
            self.GIFWidget.showText.repaint()
            self.GIFWidget.showText2.setPen(self.outColor)
            self.GIFWidget.showText2.repaint()
            self.outLineLabel.setStyleSheet('background-color:' + self.outColor)

    def setBackground(self):
        color = QColorDialog().getColor(self.config['background_color'])
        if color.isValid():
            self.config['background_color'] = color.name()
            self.GIFWidget.setBackgroundColor(self.config['background_color'])
            self.backgroundColorLabel.setStyleSheet('background-color:' + self.config['background_color'])

    def setConfig(self, config, mode, index):
        self.GIFWidget.setText(config['words'], mode)
        self.GIFWidget.showGIF.clear()
        movie = self.movieList[index]
        gifSize = self.gifSizeList[index]
        if gifSize:
            movie.setScaledSize(gifSize * config['gif_scale'] / 25)
        self.GIFWidget.showGIF.setMovie(movie)
        self.GIFWidget.setSecond(config['second'])
        self.GIFWidget.showText.setBrush(QColor(config['font_color']))
        self.GIFWidget.showText.setPen(config['out_color'])
        self.GIFWidget.showText.w = config['out_size'] / 400
        self.GIFWidget.showText.repaint()
        self.GIFWidget.showText2.setBrush(QColor(config['font_color']))
        self.GIFWidget.showText2.setPen(config['out_color'])
        self.GIFWidget.showText2.w = config['out_size'] / 400
        self.GIFWidget.showText2.repaint()
        font = QFont(config['font_name'], config['font_size'])
        if config['font_bold']:
            font.setBold(True)
        if config['font_italic']:
            font.setItalic(True)
        self.GIFWidget.setFont(font)

    def addGift(self, giftInfo):
        key = giftInfo.pop('key')
        if giftInfo['cmd'] == 'COMBO_SEND':
            if key not in self.giftExist:
                giftInfo['alive'] = 60  # 60 * 50ms = 3s
                self.giftDict[key] = giftInfo
            for key in self.giftExist:
                self.giftExist[key] -= 1
            for key in list(self.giftExist.keys()):
                if self.giftExist[key] <= 0:
                    del self.giftExist[key]
                    break
        else:
            if key not in self.giftDict:
                giftInfo['alive'] = 60  # 60 * 50ms = 3s
                self.giftDict[key] = giftInfo
            elif giftInfo['cmd'] == 'SEND_GIFT':
                self.giftDict[key]['num'] += giftInfo['num']
                self.giftDict[key]['alive'] = 60
            self.giftExist[key] = 5
        if giftInfo['type'] == 'gift' and not os.path.exists('gift/%s.png' % giftInfo['giftname']):
            size, link = giftInfo['link']
            r = requests.get(link)
            img = QPixmap.fromImage(QImage.fromData(r.content)).scaled(size, size,
                                                                       Qt.AspectRatioMode.IgnoreAspectRatio,
                                                                       Qt.TransformationMode.SmoothTransformation)
            file = QFile('gift/%s.png' % giftInfo['giftname'])
            file.open(QIODevice.WriteOnly)
            img.save(file, 'PNG')

    def play(self):
        sound = self.config[self.presetIndex]['sound_path']
        if sound:
            # self.sound.setMedia(QUrl.fromLocalFile(sound))
            self.sound.setSource(QUrl.fromLocalFile(sound))
            # self.sound.setVolume(self.config[self.presetIndex]['volume'])
            self.soundOutput.setVolume(self.config[self.presetIndex]['volume'])
            self.sound.play()
        self.GIFWidget.resize(1, 1)
        self.GIFWidget.adjust()
        self.GIFWidget.vyList = [10, 10, 10]
        self.GIFWidget.frame = self.second * 60
        self.GIFWidget.animationTimer.start()

    def playAnimate(self, giftInfo):
        self.animationToken = True
        index = 0
        giftType = giftInfo['type']
        if giftType == 'gift':
            price = giftInfo['price']
            if price == 0:
                index = self.giftPreset1.currentIndex()
            elif 0 < price <= 10:
                index = self.giftPreset2.currentIndex()
            if 10 < price <= 100:
                index = self.giftPreset3.currentIndex()
            elif 100 < price:
                index = self.giftPreset4.currentIndex()
            # self.giftPhysical.addGift(giftInfo['giftname'], giftInfo['num'], giftInfo['price'])
            self.queue.put([giftInfo['giftname'], giftInfo['num'], giftInfo['price']])
        elif giftType == 'guard':
            level = giftInfo['giftname']
            if level == '舰长':
                index = self.jianzhangPreset.currentIndex()
                # self.giftPhysical.addGift('舰长', 1, 198)
                self.queue.put(['舰长', 1, 198])
            elif level == '提督':
                index = self.tiduPreset.currentIndex()
                # self.giftPhysical.addGift('提督', 1, 1998)
                self.queue.put(['提督', 1, 1998])
            elif level == '总督':
                index = self.zongduPreset.currentIndex()
                # self.giftPhysical.addGift('总督', 1, 19998)
                self.queue.put(['总督', 1, 19998])
        elif giftType == 'sc':
            index = self.SCPreset.currentIndex()
            price = giftInfo['price']
            if price <= 30:
                # self.giftPhysical.addGift('SC30', 1, 30)
                self.queue.put(['SC30', 1, 30])
            elif price <= 50:
                # self.giftPhysical.addGift('SC50', 1, 50)
                self.queue.put(['SC50', 1, 50])
            elif price <= 100:
                # self.giftPhysical.addGift('SC100', 1, 100)
                self.queue.put(['SC100', 1, 100])
            elif price <= 500:
                # self.giftPhysical.addGift('SC500', 1, 500)
                self.queue.put(['SC500', 1, 500])
            elif price <= 1000:
                # self.giftPhysical.addGift('SC1000', 1, 1000)
                self.queue.put(['SC1000', 1, 1000])
            else:
                # self.giftPhysical.addGift('SC2000', 1, 2000)
                self.queue.put(['SC2000', 1, 2000])
        if index:
            self.presetIndex = str(index - 1)
            self.presetTab.setCurrentIndex(index - 1)
            giftInfo = [giftInfo['username'], giftInfo['num'], giftInfo['giftname'], giftInfo['price']]
            self.GIFWidget.setText(self.wordsEdit.text(), 'gift', line=1, giftInfo=giftInfo)
            self.GIFWidget.setText(self.wordsEdit2.text(), 'gift', True, line=2, giftInfo=giftInfo)
            self.play()
        else:
            self.animationToken = False

    def popKeyWords(self):
        self.keyWords.hide()
        self.keyWords.show()

    def popBilibili(self):
        QDesktopServices.openUrl(QUrl('https://www.bilibili.com/video/BV1U34y167Vm'))

    def popGitee(self):
        QDesktopServices.openUrl(QUrl('https://gitee.com/zhimingshenjun/bilibili_gifts_thanks'))

    def popOption(self):
        self.option.hide()
        self.option.show()

    # def popPVZ(self):
    #     print(sys.path[0] + '/games/PVZ/PVZ.exe')
    #     os.popen(sys.path[0] + '/games/PVZ/PVZ.exe')

    def setNoMore(self):
        self.config['check_update'] = False

    def animateFinish(self):
        self.sound.stop()
        self.animationToken = False

    def changeCenter(self, qpoint):
        self.GIFWidgetCenterPos += qpoint

    def startMonitor(self):
        if not self.executeToken:
            self.remoteThread = remoteThread(self.config['room_url'])
            self.remoteThread.giftInfo.connect(self.addGift)
            self.remoteThread.start()
            for widget in self.widgetsList:
                widget.setEnabled(False)
            self.executeToken = True
            self.GIFWidget.executeToken = True
            self.GIFWidget.gifOpacity.setOpacity(0)
            self.GIFWidget.textOpacity.setOpacity(0)
            self.GIFWidget.textOpacity2.setOpacity(0)
            self.startButton.setStyleSheet('border:2px solid #87CEFA;background-color:#3daee9')
            self.startButton.setText(self.tr('STOP TRIGGER'))
            self.timer.start()
        else:
            self.sound.stop()
            self.animationToken = False
            self.GIFWidget.animationTimer.stop()
            self.GIFWidget.showGIF.clear()
            try:
                self.GIFWidget.showGIF.setMovie(self.movie)
            except:
                pass

            self.remoteThread.terminate()
            self.remoteThread.quit()
            self.remoteThread.wait()
            self.timer.stop()

            for widget in self.widgetsList:
                widget.setEnabled(True)
            self.executeToken = False
            self.GIFWidget.executeToken = False
            self.GIFWidget.gifOpacity.setOpacity(1)
            self.GIFWidget.textOpacity.setOpacity(1)
            self.GIFWidget.textOpacity2.setOpacity(1)
            self.startButton.setStyleSheet('border:2px solid #87CEFA;background-color:#f8f9fa')
            self.startButton.setText(self.tr('START TRIGGER'))
            text = self.wordsEdit.text()
            self.GIFWidget.setText(text, 'gift', True)
            self.giftDict.clear()

    def checkGift(self):
        gift = None
        if not self.animationToken and self.giftDict:
            for k, v in self.giftDict.items():
                v['alive'] -= 1
                if v['alive'] <= 0 and not gift:
                    gift = k
        if gift:
            self.playAnimate(self.giftDict.pop(gift))

    def changeLanguage(self, language):
        self.config['language'] = language
        self.language.load('utils/%s.qm' % self.config['language'])
        self.app.installTranslator(self.language)

        self.main_widget.deleteLater()
        self.initUI()

    def updateChecker(self):
        self.updateReminder = updateReminder()
        self.updateReminder.noMoreSignal.connect(self.setNoMore)
        self.checkUpdate = checkUpdate(self.version)
        self.checkUpdate.update.connect(self.updateReminder._show)
        self.checkUpdate.start()

    def updateChecker2(self):
        self.updateReminder = updateReminder()
        self.updateReminder.noMoreSignal.connect(self.setNoMore)
        self.latestReminder = latestRemainder()
        self.checkUpdate = checkUpdate(self.version)
        self.checkUpdate.update.connect(self.updateReminder._show)
        self.checkUpdate.latest.connect(self.latestReminder._show)
        self.checkUpdate.start()


if __name__ == '__main__':
    multiprocessing.freeze_support()
    # QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    app.setStyleSheet(qdarktheme.load_stylesheet('light'))
    font = QFont('Microsoft JhengHei UI', 14, QFont.Bold)
    app.setFont(font)
    mainWindow = MainWindow(app, version=2.6)
    screen = app.primaryScreen().geometry()
    mainWindow.show()
    mainWindow.resize(800, 600)
    w, h = mainWindow.width(), mainWindow.height()
    mainWindow.move((screen.width() - w) / 2, (screen.height() - h) / 2)
    mainWindow.GIFWidget.hide()
    mainWindow.GIFWidget.show()
    w = mainWindow.GIFWidget.width()
    mainWindow.GIFWidget.move((screen.width() - w) / 2, (screen.height() - h) / 2 + 50)
    # w = mainWindow.giftPhysical.width()
    # mainWindow.giftPhysical.move(0, 0)
    sys.exit(app.exec())
